<template>
  <div id="admin-manage" class="page-wrapper">
    <!-- <div class="selector-wrapper main-card wrapper">
      <div class="main-card">
        <el-form class="form" :inline="true" ref="form" :model="formData">
          <el-form-item label="订单编号" prop="orderId">
            <el-input
              v-model.trim="formData.orderId"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model.trim="formData.userName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="userPhone">
            <el-input
              v-model.trim="formData.userPhone"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="时间选择">
            <el-date-picker
              v-model="formData.time"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="handleSubmitClick">获取数据</el-button>
    </div> -->
    <div class="wrapper main-card selector-wrapper">
      <el-button type="primary" class="add" plain @click="dialogVisible = true"
        >制作优惠券</el-button
      >
    </div>
    <div class="wrapper main-card">
      <el-table
        :data="pageData"
        style="width: 100%"
        :stripe="true"
        row-key="id"
      >
        <el-table-column prop="couponName" label="优惠券名称"></el-table-column>
        <el-table-column prop="couponLX" label="优惠券类型"></el-table-column>
        <el-table-column
          prop="couponMoney"
          label="优惠券面值"
        ></el-table-column>
        <el-table-column
          prop="leastPayMoney"
          label="优惠券最低消费"
        ></el-table-column>
        <el-table-column prop="createdAt" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createdAt | formatDate('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="couponEndTime"
          label="结束时间"
        > <template slot-scope="scope">
            <span>{{ scope.row.couponEndTime | formatDate('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleSwitchChange(scope.row, scope.$index)"
            ></el-switch>
          </template>
        </el-table-column> -->

        <el-table-column label="操作" min-width="80">
          <template #default>
            <el-button link type="primary" size="small">发布</el-button>
            <el-button link type="primary" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗 -->
      <el-dialog
        title="新增"
        :visible.sync="dialogVisible"
        width="800px"
        class="cleaner-dialog"
        :before-close="cleanSelected"
      >
        <el-form class="form" ref="form" :model="formData">
          <el-form-item label="优惠券类型">
            <el-checkbox
              v-model="checkedOptions.option1"
              @change="handleCheckboxChange('option1')"
              >通用券</el-checkbox
            >
            <el-checkbox
              v-model="checkedOptions.option2"
              @change="handleCheckboxChange('option2')"
              >商品券</el-checkbox
            >
          </el-form-item>
          <el-form-item label="优惠券名称">
            <el-input
              v-model.trim="formData.couponName"
              placeholder="请输入优惠券名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="优惠券数量">
            <el-input
              v-model.trim="formData.number"
              placeholder="请输入优惠券数量"
            ></el-input>
          </el-form-item>
          <el-form-item label="优惠券面值">
            <el-input
              v-model.trim="formData.couponMoney"
              placeholder="请输入优惠券面值"
            ></el-input>
          </el-form-item>

          <el-form-item label="优惠券门槛金额">
            <el-input
              v-model.trim="formData.leastPayMoney"
              placeholder="请输入门槛金额"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="优惠券id">
            <el-input
              v-model.trim="formData.couponUserId"
              placeholder="请输入优惠券id"
            ></el-input>
          </el-form-item> -->
          <!-- 如果需要另一个金额字段，可以修改label和v-model -->
          <el-form-item label="优惠券有效期限">
            <el-date-picker
              v-model="formData.couponEndTime"
              type="datetime"
              placeholder="选择有效期限"
              align="right"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <group-selector></group-selector>
  </div>
</template>

<script>
import GroupSelector from '@/components/GroupSelector'
import { getcoupons, addcoupons } from '@/api/pcclinet' // 确保正确导入
export default {
  name: 'RoomInfo',
  components: {
    GroupSelector
  },
  data() {
    return {
      pickerOptions: {
        // 日期时间选择器的配置选项
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '明天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      value: true,
      currentPage: 1,
      pageData: [],
      total: '',
      pageSize: 10,
      checkedOptions: {
        option1: false,
        option2: false
      },
      refundDialogVisible: false, // 控制退款确认弹窗的显示
      selectedRows: [],
      dialogVisible: false,
      formData: {
        couponName: '',
        number: '',
        couponMoney: '',
        couponEndTime: '',
        leastPayMoney: '',
        couponUserId: '',
        couponLX: ''
      },
      modifydata: {},
      tableData: [],
      currentRow: null
    }
  },

  methods: {
    //时间
    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      // 这里可以根据需要调整时间格式
      return date.toLocaleString() // 默认的本地时间格式
      // 如果你需要更具体的格式，可以使用更复杂的日期格式化方法，例如：
      // return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}
      //         ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    },
    cleanSelected(done) {
      this.$refs.form.resetFields()
      this.checkedOptions.option1 = false
      this.checkedOptions.option2 = false
      done()
    },
    handleSwitchChange(a, b) {
      //  console.log(a)
      //  console.log(this.pageData)
    },

    // 新增
    async handleSubmit() {
      try {
        // 从本地存储获取userId
        let userId = localStorage.getItem('userId')
        //  console.log('userId', userId)

        // 准备要传递给addcoupons的数据，并包括couponUserId
        let formData = {
          couponName: this.formData.couponName,
          number: this.formData.number,
          couponMoney: this.formData.couponMoney,
          couponEndTime: this.formData.couponEndTime,
          leastPayMoney: this.formData.leastPayMoney,
          couponLX: this.formData.couponLX,
          couponUserId: userId // 添加couponUserId属性，并赋值为本地存储的userId
        }

        // 调用addcoupons函数并传递表单数据
        const response = await addcoupons(formData)

        // 处理响应，弹出创建成功的提示
        alert('优惠券创建成功！')
        await getcoupons() // 直接调用导入的函数
      } catch (error) {
        console.error('错误', error) // 打印错误信息到控制台
        alert('发生了一个错误，请稍后再试。') // 显示一个简单的用户友好消息
      }
    },
    handleCheckboxChange(option) {
      if (option === 'option1') {
        // 如果通用券被选中
        this.formData.couponLX = this.checkedOptions.option1 ? 1 : ''
      } else if (option === 'option2') {
        // 如果商品券被选中
        this.formData.couponLX = this.checkedOptions.option2 ? 2 : ''
      }
    },
    fetchData() {
      getSomeData().then(response => {
        // 确保 response.data 是数组
        this.tableData = response.data || []
        this.total = response.total || 0 // 也确保 total 是数字
      })
    },
    // Implement pagination methods
    queryByPage() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = this.currentPage * this.pageSize
      return this.tableData.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageData = this.queryByPage()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageData = this.queryByPage()
    },
    // Search button click handler
    handleSubmitClick() {
      const { orderId, userName, userPhone, time } = this.formData
      const strTime = time.length ? time[0] : ''
      const endTime = time.length ? time[1] : ''

      // Call API with form data
      getcoupons({ orderId, userName, userPhone, strTime, endTime })
        .then(res => {
          if (res.success) {
            this.tableData = res.data
            this.total = res.data.length
            this.pageData = this.queryByPage()
          }
        })
        .catch(err => {
          console.error('Error fetching data:', err)
        })
    },

    handleRefundOrder() {
      this.refundDialogVisible = true
    }
  },

  mounted() {
    // Initial data fetch
    getcoupons().then(res => {
      if (res.success) {
        //  console.log(res.data)
        this.tableData = res.data
        this.total = res.data.length
        this.pageData = res.data.coupons
        this.pageData = this.queryByPage()
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  margin: 40px 0;
}

.selector-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* Vertical center alignment */
}

.list-wrapper {
  margin-top: 40px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}

.form-item-wrapper {
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  /* Adjust margin as needed */
}

.image-preview {
  max-width: 100px;
  /* Adjust as needed */
  max-height: 50px;
  /* Adjust as needed */
}

.button-wrapper {
  margin-top: 20px;
  /* Adjust margin as needed */
  display: flex;
  justify-content: flex-end;
  /* Align to right */
  align-items: center;
  /* Vertical center alignment */
}
</style>
